package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuiliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListtener extends AnalysisEventListener<SubjectData> {

    //这个类无法交给spring管理

    public EduSubjectService subjectService;

    public SubjectExcelListtener() {}
    public SubjectExcelListtener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //读取excel内容，添加到数据库中
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            throw new GuiliException(20001,"文件为空！！！");
        }
        System.out.println("数据不为空");
        //一行一行读取·，每次读两个，第一个值为一级分类，第二个为二级分类
        //一级分类的添加
        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubejctName());
        if(existOneSubject==null){
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubejctName());
            subjectService.save(existOneSubject);
        }
        String pid = existOneSubject.getId();
        //二级分类的添加
        EduSubject exisTwoSubject = this.exisTwoSubject(subjectService,subjectData.getTwoSubejctName(),pid);
        if(exisTwoSubject==null){
            exisTwoSubject=new EduSubject();
            exisTwoSubject.setParentId(pid);
            exisTwoSubject.setTitle(subjectData.getTwoSubejctName());
            subjectService.save(exisTwoSubject);
        }
    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject( EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return  oneSubject;
    }
    //判断二级分类不能重复添加
    private EduSubject exisTwoSubject( EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return  twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
